﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Net;
using System.Drawing;
using CIRDiagnoseDevice.DBManage;
using System.Threading;

namespace CIRDiagnoseDevice.Test
{
    class GSM_RFunTrial
    {
        #   region 全局变量
        public bool UDPConnectStatus;
        private int Cycle;
        SerialPort OSP7;
        SerialPort OSP6;
        Form form;
        public int ReadedNum = 0; // 记录接收返回数据的次数
        public int CycleTimes = 0;
        private string TestTime, DevNum, Tester;
        private byte[] RBuffer = new byte[500]; // 接收测试仪返回结果
        private DataGridView dataGridView1;
        private List<byte> RXBffer = new List<byte>();//缓冲接收数据
        private InitSerialPort InitPort = new InitSerialPort();
        private int Index;
        private bool IsReceiveTrainNum;
        private bool CheckStatus;
        private CommunicationWithInterfaceUnit Unit = new CommunicationWithInterfaceUnit();
        private string GPRS_ConnName;
        private string GPRS_CabNum;
        private bool TestDispacthComm;
        private bool TestWirelessTrainNum;
        private bool TestTrainRouteNotice;
        private string IPStr;
        private int PortNum;
        private string SourceIP;
        private int StartIndex; // 指定测试结果填入表中的初始行索引
        private SendTaxData sendTaxData = new SendTaxData();
        public event MessageNotice OnMessageNotice;
        private string ToolStripInfo;
        private bool Flag; // 标志是否开始处理接收数据
        int Num;  //标志接收数据字节数
        private delegate void formShow(TaxForm form);
        #   endregion

        public GSM_RFunTrial(Form form, DataGridView dataGridView1, int startIndex, SerialPort OSP, SerialPort OSP2)
        {
            this.dataGridView1 = dataGridView1;
            this.form = form;
            this.StartIndex = startIndex;
            OSP7 = OSP;
            OSP6 = OSP2;
            // InitPort.Open(OSP6);

            InitPort.Open(OSP7);
        }



        public void ClearSource()
        {
            OSP7.Close();
            OSP6.Close();
            OSP7.DataReceived -= new SerialDataReceivedEventHandler(OSP7_DataReceived);
            GC.Collect();
        }

        public void InitParameter()
        {
            ReadedNum = 0;
            Cycle = 0;
            CycleTimes = 0;
            Index = 0;
            Num = 0;
            UDPConnectStatus = false;
            if (MainFrm.MotherFrm.IsTestTotal == false)
            {
                OSP7.DataReceived -= new SerialDataReceivedEventHandler(OSP7_DataReceived);
            }
            TestDispacthComm = false;
            TestWirelessTrainNum = false;
            TestTrainRouteNotice = false;
            IsReceiveTrainNum = false;
            MainFrm.MotherFrm.StopTest = false;
            MainFrm.MotherFrm.Suspend = false;
            OSP7.ReadTimeout = 90000;
            Array.Clear(RBuffer, 0, RBuffer.Length);
            RXBffer.Clear();
            MainFrm.MotherFrm.GSM_RFunTrial = false;
            if (MainFrm.MotherFrm.IsTestTotal == false)
            {
                OSP7.DataReceived += new SerialDataReceivedEventHandler(OSP7_DataReceived);
            }
            Flag = false;
        }

        public void StartGsmFunTrial()
        {
            InitParameter();
            if (MessageBox.Show("现在进行GSM-R数据模块功能试验，请选择GSM-R模式运行线路\r\n并将CIR综合测试设备上接口单元的TAX数据口与CIR的TDCS入连接！", "用户操作提示", MessageBoxButtons.OK) == DialogResult.OK)
            {
                MainFrm.MotherFrm.ResetGPRS_Mod();
                Delay(1000);
                SendWirelessTrainNumCommand();
                //for (int i = 0; i < 100; i++)
                //{
                //    byte[] data = sendTaxData.SendDigData(0x04, (ushort)65);
                //    OSP6.Write(data, 0, data.Length);
                //    Delay(500);
                //}
            }
            ToolStripInfo = "正在试验GSM-R数据模块功能";
            MainFrm.MotherFrm.SetToolStrip(ToolStripInfo);
        }

        private void OpenFrm()
        {
            TaxForm taxform = new TaxForm();
            taxform.Show();
        }

        # region 功能试验过程处理

        public void DealWithData()
        {
            string str2 = string.Empty;
            string str = string.Empty;
            string commStr = string.Empty;
            int length = 0;
            try
            {
                while (!MainFrm.MotherFrm.StopTest)
                {
                    if (!Flag)
                        continue;
                    int index = RXBffer.IndexOf(0x0A);//Array.IndexOf(RXBuffer, (byte)0x0A, 0, length);

                    if (ReadedNum != 12)
                    {
                        string[] strArr;
                        if (index == -1 && !IsReceiveTrainNum)
                        {
                            if (ReadedNum == 0)
                            {
                                commStr = "ATE0\r\n";
                                byte[] sendComm5 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                                OSP7.Write(sendComm5, 0, sendComm5.Length);
                            }
                            else if (ReadedNum == 1)
                            {
                                commStr = "ATE0\r\n";
                                byte[] sendComm5 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                                OSP7.Write(sendComm5, 0, sendComm5.Length);
                            }
                            continue;

                        }
                        else
                        {
                            byte[] data = RXBffer.ToArray();
                            // Array.Copy(RXBffer.GetRange(0, Num).ToArray(), 0, data, 0, Num) ;
                            str = System.Text.ASCIIEncoding.Default.GetString(data, 0, data.Length);
                            str = str.Trim(new Char[] { '\r', '\n' });
                            strArr = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            RXBffer.RemoveRange(0, RXBffer.Count);
                            Index = 0;
                            length = 0;
                        }

                        if (strArr.Length >= 2)
                        {
                            if (ReadedNum == 4 || ReadedNum == 9 || ReadedNum == 0)
                            {
                                str = strArr[0];
                                str2 = strArr[1];
                            }
                            else
                            {
                                str = strArr[1];//strArr[strArr.Length - 1];
                            }
                        }
                        else if (str != "")
                        {
                            str = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)[0];
                        }
                        else
                        {
                            continue;
                        }
                    }
                    if (CheckStatus)
                    {
                        if (str == "STATE: CONNECT OK" || str == "ALREADY CONNECT")
                            UDPConnectStatus = true;
                        else if (str == "ERROR")
                        {
                            commStr = "AT+CIPSTATUS\r\n";
                            byte[] sendComm = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm, 0, sendComm.Length);
                            Delay(1500);
                        }
                        else if (str == "STATE: PDP DEACT")
                        {
                            UDPConnectStatus = false;
                        }
                        CheckStatus = false;
                    }

                    if (ReadedNum == 0)
                    {
                        if (str == "ERROR" || str == "CLOSE OK" || str == "OK")
                        {
                            commStr = "ATE0\r\n";
                            byte[] sendComm5 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm5, 0, sendComm5.Length);
                            Delay(2500);
                            ReadedNum++;
                        }
                        else if (str == "ERROR")
                        {
                            commStr = "AT\r\n";
                            byte[] sendComm4 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm4, 0, sendComm4.Length);
                            Delay(2500);
                        }
                        else
                        {
                            commStr = "AT\r\n";
                            byte[] sendComm5 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm5, 0, sendComm5.Length);
                            Delay(2500);
                            ReadedNum++;
                        }
                    }
                    else if (ReadedNum == 1)
                    {
                        if (str == "OK")
                        {
                            commStr = "AT+CREG=1\r\n";
                            byte[] sendComm = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm, 0, sendComm.Length);
                            Delay(2500);
                            ReadedNum++;
                        }
                        else if (str == "ERROR")
                        {
                            commStr = "ATE0\r\n";
                            byte[] sendComm5 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm5, 0, sendComm5.Length);
                            Delay(2500);
                        }
                        else
                        {
                            commStr = "ATE0\r\n";
                            byte[] sendComm5 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm5, 0, sendComm5.Length);
                            Delay(2500);
                        }
                    }
                    else if (ReadedNum == 2)
                    {
                        if (str == "OK")
                        {
                            commStr = "AT+CGREG=1\r\n";
                            byte[] sendComm2 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm2, 0, sendComm2.Length);
                            Delay(2500);
                            ReadedNum++;
                        }
                        else if (str == "ERROR")
                        {
                            commStr = "AT+CREG=1\r\n";
                            byte[] sendComm = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm, 0, sendComm.Length);
                            Delay(2500);
                        }
                        else
                        {
                            commStr = "AT+CREG=1\r\n";
                            byte[] sendComm = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm, 0, sendComm.Length);
                            Delay(2500);
                        }
                    }
                    else if (ReadedNum == 3)
                    {
                        if (str == "OK")
                        {
                            commStr = "AT+CGREG?\r\n";
                            byte[] sendComm3 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm3, 0, sendComm3.Length);
                            Delay(2500);
                            ReadedNum++;
                        }
                        else if (str == "ERROR")
                        {
                            commStr = "AT+CGREG=1\r\n";
                            byte[] sendComm4 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm4, 0, sendComm4.Length);
                            Delay(2500);
                        }
                        else
                        {
                            commStr = "AT+CGREG=1\r\n";
                            byte[] sendComm2 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm2, 0, sendComm2.Length);
                            Delay(2500);
                        }

                    }
                    else if (ReadedNum == 4)
                    {

                        if ((str == "+CGREG: 1,1" && str2 == "OK") || str == "+CGATT:1" || str == "OK")
                        {
                            commStr = "AT+CLPORT=\"UDP\",\"20001\"\r\n";
                            byte[] sendComm6 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm6, 0, sendComm6.Length);
                            Delay(2500);
                            CycleTimes = 0;
                            ReadedNum++;
                        }
                        else
                        {
                            if (Cycle == 0)
                            {
                                commStr = "AT+CGREG?\r\n";
                                byte[] sendComm5 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                                OSP7.Write(sendComm5, 0, sendComm5.Length);
                                Delay(1500);
                                Cycle++;
                            }
                            else
                            {
                                commStr = "ATE0\r\n";
                                byte[] sendComm5 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                                OSP7.Write(sendComm5, 0, sendComm5.Length);
                                Delay(1500);
                                ReadedNum = 0;
                            }
                        }
                    }
                    else if (ReadedNum == 5)
                    {
                        if (str == "OK")
                        {
                            GPRS_ConnSet GPRS_Set = new GPRS_ConnSet();
                            GPRS_Set.ShowDialog();
                            GPRS_ConnName = GPRS_Set.GPRS_ConnName;
                            GPRS_CabNum = GPRS_Set.GPRS_CabNum;
                            commStr = "AT+CSTT=\"" + GPRS_ConnName + "\"" + "," + "\"" + GPRS_CabNum + "\"" + "," + "\"" + GPRS_CabNum + "\"\r\n";
                            byte[] sendComm8 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm8, 0, sendComm8.Length);
                            Delay(2500);
                            ReadedNum++;
                        }
                        else if (str == "ERROR")
                        {
                            commStr = "AT+CLPORT=\"UDP\",\"20001\"\r\n";
                            byte[] sendComm9 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm9, 0, sendComm9.Length);
                            Delay(2500);
                        }
                    }
                    else if (ReadedNum == 6)
                    {
                        if (CycleTimes == 0)
                        {
                            if (str == "OK")
                            {
                                commStr = "AT+CIICR\r\n";
                                byte[] sendComm10 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                                OSP7.Write(sendComm10, 0, sendComm10.Length);
                                Delay(2500);
                                ReadedNum++;
                            }
                            else if (str == "ERROR")
                            {

                                CycleTimes++;
                                commStr = "AT+CIPSHUT\r\n";
                                byte[] sendComm12 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                                OSP7.Write(sendComm12, 0, sendComm12.Length);
                                Delay(2500);

                            }

                        }
                        else
                        {
                            commStr = "AT+CSTT=\"" + GPRS_ConnName + "\"" + "," + "\"" + GPRS_CabNum + "\"" + "," + "\"" + GPRS_CabNum + "\"\r\n";
                            byte[] sendComm11 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm11, 0, sendComm11.Length);
                            Delay(2500);
                            CycleTimes = 0;
                        }
                    }
                    else if (ReadedNum == 7)
                    {
                        if (str == "OK")
                        {
                            commStr = "AT+CIFSR\r\n";
                            byte[] sendComm12 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm12, 0, sendComm12.Length);
                            Delay(2500);
                            ReadedNum++;
                        }
                        else if (str == "ERROR")
                        {
                            commStr = "AT+CIICR\r\n";
                            byte[] sendComm13 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm13, 0, sendComm13.Length);
                            Delay(2500);
                        }
                    }
                    else if (ReadedNum == 8)
                    {
                        if ((IPAddress.Parse(str) is IPAddress))
                        {
                            SourceIP = str;
                            commStr = "AT+CIPSTATUS\r\n";
                            byte[] sendComm14 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm14, 0, sendComm14.Length);
                            MainFrm.MotherFrm.ShowIP(SourceIP);
                            Delay(2500);
                            ReadedNum++;
                        }
                        else
                        {
                            commStr = "AT+CIFSR\r\n";
                            byte[] sendComm15 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm15, 0, sendComm15.Length);
                            Delay(2500);
                        }
                    }
                    else if (ReadedNum == 9)
                    {
                        if (str == "OK" && str2 == "STATE: IP STATUS")
                        {
                            IPSet destIP = new IPSet();
                            destIP.ShowDialog();
                            IPStr = destIP.IPStr;
                            commStr = "AT+CIPSTART=\"UDP\",\"" + IPStr + "\"," + "\"20000\"\r\n";
                            byte[] sendComm16 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm16, 0, sendComm16.Length);
                            Delay(2500);
                            ReadedNum++;
                        }
                        else
                        {
                            commStr = "AT+CIPSTATUS\r\n";
                            byte[] sendComm17 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm17, 0, sendComm17.Length);
                            Delay(2500);
                        }
                    }
                    else if (ReadedNum == 10)
                    {
                        if ((str == "CONNECT OK") || str == "ALREADY CONNECT")
                        {
                            commStr = "AT+CIPSTATUS\r\n";
                            byte[] sendComm17 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm17, 0, sendComm17.Length);
                            Delay(2500);
                            ReadedNum++;
                            TestWirelessTrainNum = true;
                        }
                        else
                        {
                            if (IPStr == "")
                            {
                                IPSet destIP = new IPSet();
                                destIP.ShowDialog();
                                IPStr = destIP.IPStr;
                            }
                            commStr = "AT+CIPSTART=\"UDP\",\"" + IPStr + "\"," + "\"20000\"\r\n";
                            byte[] sendComm16 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm16, 0, sendComm16.Length);
                            Delay(2500);
                        }
                    }
                    else if (ReadedNum == 11)
                    {
                        if (str == "STATE: CONNECT OK" || str == "ALREADY CONNECT")
                        {
                            UDPConnectStatus = true;
                            CycleTimes = 0;

                            if (TestWirelessTrainNum)
                            {
                                Index = 0;
                                ReadedNum++;
                                IsReceiveTrainNum = true;
                                MessageBox.Show("请将状态栏上的IP地址输入到CIR的GRIS IP与主用GROS IP地址栏里！", "提示");
                                for (int i = 0; i < 15; i++)
                                {
                                    byte[] data = sendTaxData.SendDigData(0x04, (ushort)65);
                                    OSP6.Write(data, 0, data.Length);
                                    Delay(200);
                                }
                            }

                        }
                        else
                        {
                            commStr = "AT+CIPCLOSE\r\n";
                            byte[] sendComm17 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                            OSP7.Write(sendComm17, 0, sendComm17.Length);
                            Delay(1500);
                            ReadedNum = 0;
                        }
                    }
                    else if (ReadedNum == 12)
                    {
                        if (TestWirelessTrainNum && IsReceiveTrainNum)
                        {
                            //Delay(2000);
                            if(RXBffer.Count == 0)
                            {
                                byte[] data = sendTaxData.SendDigData(0x04, (ushort)65);
                                OSP6.Write(data, 0, data.Length);
                            }
                            DealWithWirelessTrainNum(RBuffer, Num);
                        }
                        else if (TestDispacthComm)
                        {
                           // if (str == "SEND OK")
                            {
                                if (MessageBox.Show("请观察MMI是否收到调度命令", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {

                                    FillGridWithJudgeResult(dataGridView1, 1 + StartIndex, "合格", true);
                                    SendTrainRouteForenoticeCommand();
                                    TestDispacthComm = false;
                                }
                                else
                                {
                                    if (CycleTimes == 0)
                                    {
                                        CycleTimes++;
                                        SendDispatchCommand();
                                    }
                                    else
                                    {
                                        CycleTimes = 0;
                                        if (MessageBox.Show("请观察MMI是否收到调度命令", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            FillGridWithJudgeResult(dataGridView1, 1 + StartIndex, "合格", true);
                                            SendTrainRouteForenoticeCommand();
                                            TestDispacthComm = false;
                                        }
                                        else
                                        {
                                            FillGridWithJudgeResult(dataGridView1, 1 + StartIndex, "不合格", false);
                                            SendTrainRouteForenoticeCommand();
                                            TestDispacthComm = false;
                                        }
                                    }
                                }
                                TestTrainRouteNotice = true;
                            }
                        }
                        else if (TestTrainRouteNotice)
                        {
                           // if (str == "SEND OK")
                            {
                                if (MessageBox.Show("请观察MMI是否收到列车进路信息命令", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    FillGridWithJudgeResult(dataGridView1, 2 + StartIndex, "合格", true);
                                    TestTrainRouteNotice = false;
                                    MainFrm.MotherFrm.GSM_RFunTrial = false;
                                    MainFrm.MotherFrm.GSM_RFunTrialSaved = false;
                                    ToolStripInfo = "GSM-R数据模块功能试验完成";
                                    MainFrm.MotherFrm.SetToolStrip(ToolStripInfo);
                                    MessageBox.Show("GSM-R数据模块功能试验完成！");
                                    commStr = "AT+CGREG=2\r\n";
                                    byte[] sendComm2 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                                    OSP7.Write(sendComm2, 0, sendComm2.Length);
                                    Delay(2500);
                                    OSP7.DataReceived -= new SerialDataReceivedEventHandler(OSP7_DataReceived);
                                    if (MainFrm.MotherFrm.IsTestTotal)
                                    {
                                        MainFrm.MotherFrm.WholeFunTrialSaved = false;
                                        MainFrm.MotherFrm.TestTotalSaved = false;
                                    }
                                    else
                                    {
                                        MainFrm.MotherFrm.ChangeButtonText();
                                        MainFrm.MotherFrm.StopTest = true;
                                        MainFrm.MotherFrm.Suspend = true;
                                        OSP7.Close();
                                    }
                                    if (OnMessageNotice != null)
                                    {
                                        OnMessageNotice(this, ThreadRunState.End);
                                    }
                                    TestTrainRouteNotice = false;
                                    Flag = false;
                                    return;
                                }
                                else
                                {
                                    if (CycleTimes == 0)
                                    {
                                        CycleTimes++;
                                        SendTrainRouteForenoticeCommand();
                                    }
                                    else
                                    {
                                        CycleTimes = 0;
                                        if (MessageBox.Show("请观察MMI是否收到列车进路信息命令", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            FillGridWithJudgeResult(dataGridView1, 2 + StartIndex, "合格", true);
                                            TestTrainRouteNotice = false;
                                        }
                                        else
                                        {
                                            FillGridWithJudgeResult(dataGridView1, 2 + StartIndex, "不合格", false);
                                            TestTrainRouteNotice = false;
                                        }
                                        TestTrainRouteNotice = false;
                                        MainFrm.MotherFrm.GSM_RFunTrial = false;
                                        MainFrm.MotherFrm.GSM_RFunTrialSaved = false;
                                        ToolStripInfo = "GSM-R数据模块功能试验完成";
                                        MainFrm.MotherFrm.SetToolStrip(ToolStripInfo);
                                        MessageBox.Show("GSM-R数据模块功能试验完成！");
                                        commStr = "AT+CGREG=2\r\n";
                                        byte[] sendComm2 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                                        OSP7.Write(sendComm2, 0, sendComm2.Length);
                                        Delay(2500);
                                        OSP7.DataReceived -= new SerialDataReceivedEventHandler(OSP7_DataReceived);
                                        if (MainFrm.MotherFrm.IsTestTotal)
                                        {
                                            MainFrm.MotherFrm.WholeFunTrialSaved = false;
                                            MainFrm.MotherFrm.TestTotalSaved = false;
                                        }
                                        else
                                        {
                                            MainFrm.MotherFrm.ChangeButtonText();
                                            MainFrm.MotherFrm.StopTest = true;
                                            MainFrm.MotherFrm.Suspend = true;
                                            OSP7.Close();
                                        }
                                        if (OnMessageNotice != null)
                                        {
                                            OnMessageNotice(this, ThreadRunState.End);
                                        }
                                        Flag = false;
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {

            }
        }

        # endregion

        #region 处理调度命令模块
        private void OSP7_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            while (!MainFrm.MotherFrm.StopTest)
            {
                while (!MainFrm.MotherFrm.Suspend)
                {
                    if (MainFrm.MotherFrm.GSM_RFunTrial)
                    {
                        try
                        {
                            Num = OSP7.Read(RBuffer, 0, RBuffer.Length);
                            Index += Num;
                            if (RXBffer.Count > 1024)
                            {
                                RXBffer.Clear();
                            }
                            byte[] recerData = new byte[Num];
                            Array.Copy(RBuffer, 0, recerData, 0, Num);
                            RXBffer.AddRange(recerData);
                            Flag = true;
                        }
                        catch (System.Exception ex)
                        {
                            if (ex.GetType() == typeof(TimeoutException))
                            {
                                if (Cycle != 2)
                                {
                                    StartGsmFunTrial();
                                    Cycle++;
                                }
                                else
                                {
                                    if (OnMessageNotice != null)
                                    {
                                        OnMessageNotice(this, ThreadRunState.End);
                                    }
                                    Flag = false;
                                    MessageBox.Show("无法接收到数据请重新更换SIM卡后或调整天线位置后请重新测试！", "提示");
                                    MainFrm.MotherFrm.ChangeButtonText();
                                    return;
                                }
                            }
                            if (ReadedNum == 12)
                            {
                                string commStr = string.Empty;
                                
                                if (CycleTimes == 0 && IsReceiveTrainNum)
                                {
                                    FillGridWithJudgeResult(dataGridView1, 0 + StartIndex, "不合格", false);
                                    SendDispatchCommand();
                                    CycleTimes++;
                                }
                                else if (CycleTimes == 1)
                                {
                                    TestTrainRouteNotice = true;
                                    if (TestTrainRouteNotice)
                                    {
                                        FillGridWithJudgeResult(dataGridView1, 1 + StartIndex, "不合格", false);
                                        SendTrainRouteForenoticeCommand();
                                        TestDispacthComm = false;
                                        CycleTimes++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        #endregion

        //将测试判断结果填写到测试表中
        private void FillGridWithJudgeResult(DataGridView gridview, int rowIndex, string result, bool isGreen)
        {
            if (gridview.InvokeRequired)
            {
                gridview.Invoke(new MethodInvoker(delegate
                {
                    gridview.Rows[rowIndex].Cells["试验结果"].Value = result;
                    if (isGreen)
                        gridview.Rows[rowIndex].Cells["试验结果"].Style.ForeColor = Color.Green;
                    else
                        gridview.Rows[rowIndex].Cells["试验结果"].Style.ForeColor = Color.Red;
                    gridview.Refresh();
                }));
            }
            else
            {
                gridview.Rows[rowIndex].Cells["试验结果"].Value = result;
                if (isGreen)
                    gridview.Rows[rowIndex].Cells["试验结果"].Style.ForeColor = Color.Green;
                else
                    gridview.Rows[rowIndex].Cells["试验结果"].Style.ForeColor = Color.Red;
                gridview.Refresh();
            }
        }


        #region 处理无线车此号数据
        private void DealWithWirelessTrainNum(byte[] readByte, int length)
        {
            try
            {
                int startIndex;
                if (Index + length > 1024)
                {
                    Index = 0;
                    Array.Clear(readByte, 0, length);
                }
                // Array.Copy(readByte, 0, RXBuffer, Index, length);
                RXBffer.AddRange(readByte);
                Index += length;
                startIndex = FindDataFrameHead(RXBffer.ToArray(), (byte)0x10, (byte)0x02, 0, Index, true);
                if (startIndex < 0)
                    return;

                int endIndex = FindDataFrameHead(RXBffer.ToArray(), (byte)0x10, (byte)0x03, startIndex, Index, false);
                if (endIndex < 0)
                    return;
                if (startIndex > endIndex)
                    return;//endIndex = FindDataFrameHead(RXBuffer, (byte)0x10, (byte)0x03, Index - 1, Index, false);
                if (endIndex < 0)
                    return;
                int len = endIndex - startIndex + 2;
                byte[] readData = new byte[length];
                //Array.Copy(RXBuffer, startIndex, readData, 0, len);
                readByte = RXBffer.GetRange(startIndex, len).ToArray();
                //Array.Clear(RXBuffer, 0, endIndex);
                Index = 0;
                byte[] realData = Unit.DePacketData(readByte);
                RXBffer.RemoveRange(0, endIndex);
                //byte[] realData = DePacketData(readData);
                //if (realData.Length > 72)
                {
                    if (realData[14] == 0x05 && realData[15] == 0x21)
                    {
                        string trainType = System.Text.ASCIIEncoding.Default.GetString(realData, 40, 4);
                        int trainNum = realData[44] + (realData[45] << 8) + (realData[46] << 16);// (byte)(((byte)(realData[44] >> 4)) << 4) + (byte)(((byte)(realData[44] << 4)) >> 4) + (byte)(((byte)(realData[45] >> 4)) << 4) + (byte)(((byte)(realData[45] << 4)) >> 4) + (byte)(((byte)(realData[46] >> 4)) << 4) + (byte)(((byte)(realData[46] << 4)) >> 4);
                        if (trainNum == int.Parse(TaxDataTrainNumAndCabNo.TrainNum))
                        {
                            IsReceiveTrainNum = false;
                            TestWirelessTrainNum = false;
                            // if (MessageBox.Show("接收到的车次号与TAX数据发送的车次号一致，是否包存测试结果", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                FillGridWithJudgeResult(dataGridView1, 0 + StartIndex, "合格", true);
                                SendDispatchCommand();
                            }
                        }
                        else
                        {
                            IsReceiveTrainNum = false;
                            TestWirelessTrainNum = false;
                            FillGridWithJudgeResult(dataGridView1, 0 + StartIndex, "不合格", false);
                            SendDispatchCommand();
                        }
                        TestDispacthComm = true;
                    }
                    //else if (realData[14] == 0x0f && realData[15] == 0x01)//判断是否是申请GRISIP地址
                    //{
                    //    byte[] dataByte = SendGrisIP();
                    //    byte[] sendByte = Unit.PacketData(dataByte);
                    //    OSP7.Write(sendByte, 0, sendByte.Length);
                    //}
                }
            }
            catch
            {

            }
        }
        #endregion

        //延时多少毫秒
        public static void Delay(int mSecond)
        {
            int last_start;

            last_start = Environment.TickCount;
            while ((Environment.TickCount - last_start) <= mSecond)
            {
                System.Windows.Forms.Application.DoEvents();
            }
        }

        //返回GRISIP地址
        private byte[] SendGrisIP()
        {
            List<byte> dataList = new List<byte>();
            IPAddress sIP;
            //IPAddress.TryParse("61.141.105.68", out sIP);
            IPAddress.TryParse(SourceIP, out sIP);
            byte[] ipByte = sIP.GetAddressBytes();
            IPAddress dIP;
            //IPAddress.TryParse("10.232.197.36", out dIP);
            IPAddress.TryParse(IPStr, out dIP);
            byte[] ipByte2 = dIP.GetAddressBytes();
            dataList.Add(0x27);
            dataList.Add(0x04);
            for (int i = 0; i < ipByte.Length; i++)
            {
                dataList.Add(ipByte[i]);
            }
            dataList.Add(0x01);
            dataList.Add(0x04);
            for (int i = 0; i < ipByte2.Length; i++)
            {
                dataList.Add(ipByte2[i]);
            }
            dataList.Add(0x0f);
            dataList.Add(0x81);
            for (int i = 0; i < ipByte.Length; i++)
            {
                dataList.Add(ipByte[i]);
            }
            return dataList.ToArray();
        }

        #region 调度命令数据
        private byte[] DispatchCommand()
        {
            try
            {
                List<byte> data = new List<byte>();
                IPAddress sIP;
                //IPAddress.TryParse("61.141.105.68", out sIP);
                IPAddress.TryParse(SourceIP, out sIP);
                byte[] ipByte = sIP.GetAddressBytes();
                IPAddress dIP;
                //IPAddress.TryParse("10.232.197.36", out dIP);
                IPAddress.TryParse(IPStr, out dIP);
                byte[] ipByte2 = dIP.GetAddressBytes();
                byte year = (byte)(System.DateTime.Now.Year % 20);
                byte month = (byte)(System.DateTime.Now.Month);
                byte day = (byte)(System.DateTime.Now.Day);
                string content = "调度命令测试";
                byte[] contentByte = System.Text.ASCIIEncoding.Default.GetBytes(content);

                data.Add(0x23);
                data.Add(0x04);
                data.Add(ipByte[0]);
                data.Add(ipByte[1]);
                data.Add(ipByte[2]);
                data.Add(ipByte[3]);
                data.Add(0x02);
                data.Add(0x04);
                data.Add(ipByte2[0]);
                data.Add(ipByte2[1]);
                data.Add(ipByte2[2]);
                data.Add(ipByte2[3]);
                data.Add(0x06);
                data.Add(0x20);
                data.Add(0x01);
                data.Add((byte)HexToBCD(year, 2));
                data.Add((byte)HexToBCD(month, 2));
                data.Add((byte)HexToBCD(day, 2));
                byte hour = (byte)HexToBCD((ulong)System.DateTime.Now.Hour, 2);
                byte minute = (byte)HexToBCD((ulong)System.DateTime.Now.Minute, 2);
                byte second = (byte)HexToBCD((ulong)System.DateTime.Now.Second, 2);
                data.Add(hour);
                data.Add(minute);
                data.Add(second);
                data.Add(hour);
                data.Add(minute);
                data.Add(second);
                string trNum = TaxDataTrainNumAndCabNo.TrainType + TaxDataTrainNumAndCabNo.TrainNum.ToString();
                if (trNum == "0")
                {
                    TrainNumAndCabNum trainNum = new TrainNumAndCabNum();
                    trainNum.ShowDialog();
                    trNum = trainNum.TrainNum;
                }
                byte[] trNumByte = System.Text.ASCIIEncoding.Default.GetBytes(trNum);
                int len = trNumByte.Length;
                for (int i = 0; i < len; i++)
                {
                    data.Add(trNumByte[i]);
                }
                for (int i = 0; i < 7 - len; i++)
                {
                    data.Add(0x20);
                }
                string cabNo = TaxDataTrainNumAndCabNo.CabType + TaxDataTrainNumAndCabNo.CabNo;
                if (cabNo == "" || cabNo == null)
                {
                    CabNO cn = new CabNO();
                    cn.ShowDialog();
                    cabNo = cn.CabStr;
                }
                byte[] cabByte = System.Text.ASCIIEncoding.Default.GetBytes(cabNo);//(GPRS_CabNum);
                int len2 = cabByte.Length;
                for (int i = 0; i < 3; i++)
                {
                    data.Add(cabByte[i]);
                }
                for (int i = 4; i >= 0; i--)
                {
                    if (i >= len2 - 3)
                        data.Add(0x20);
                    else
                        data.Add(cabByte[len2 - i - 1]);
                }
                data.Add(0x01);
                data.Add(0x31);
                data.Add(0x31);
                data.Add(0x32);
                for (int i = 0; i < 11; i++)
                {
                    data.Add(0x20);
                }
                for (int i = 0; i < 6; i++)
                {
                    data.Add(0x00);
                }
                data.Add(0x01);
                data.Add(0x01);
                data.Add(0xC1);
                data.Add(0xD0);
                data.Add(0xB3);
                data.Add(0xB5);
                data.Add(0xBD);
                data.Add(0xF8);
                data.Add(0xC2);
                data.Add(0xB7);
                data.Add(0xD4);
                data.Add(0xA4);
                data.Add(0xB8);
                data.Add(0xE6);
                data.Add(0x0D);
                data.Add(0x0A);
                data.Add(0xCF);
                data.Add(0xC2);
                data.Add(0xD7);
                data.Add(0xAF);
                data.Add(0xD5);
                data.Add(0xBE);
                data.Add(0x0D);
                data.Add(0x0A);
                for (int i = 0; i < contentByte.Length; i++)
                {
                    data.Add(contentByte[i]);
                }
                byte[] frameData = data.ToArray();
                byte[] sendData = Unit.PacketData(frameData);
                return sendData;
                //OSP7.Write(sendData, 0, sendData.Length);
            }
            catch (System.Exception ex)
            {
                return null;
            }
        }

        //列车进路信息
        private byte[] TrainRouterCommand()
        {
            try
            {
                List<byte> data = new List<byte>();
                IPAddress sIP;
                //IPAddress.TryParse("61.141.105.68", out sIP);
                IPAddress.TryParse(SourceIP, out sIP);
                byte[] ipByte = sIP.GetAddressBytes();
                IPAddress dIP;
                // IPAddress.TryParse("10.232.197.36", out dIP);
                IPAddress.TryParse(IPStr, out dIP);
                byte[] ipByte2 = dIP.GetAddressBytes();
                byte year = (byte)(System.DateTime.Now.Year % 20);
                byte month = (byte)(System.DateTime.Now.Month);
                byte day = (byte)(System.DateTime.Now.Day);
                string content = "列车进路信息测试";
                byte[] contentByte = System.Text.ASCIIEncoding.Default.GetBytes(content);

                data.Add(0x23);
                data.Add(0x04);
                data.Add(ipByte[0]);
                data.Add(ipByte[1]);
                data.Add(ipByte[2]);
                data.Add(ipByte[3]);
                data.Add(0x02);
                data.Add(0x04);
                data.Add(ipByte2[0]);
                data.Add(ipByte2[1]);
                data.Add(ipByte2[2]);
                data.Add(ipByte2[3]);
                data.Add(0x06);
                data.Add(0x20);
                data.Add(0x07);
                data.Add((byte)HexToBCD(year, 2));
                data.Add((byte)HexToBCD(month, 2));
                data.Add((byte)HexToBCD(day, 2));
                byte hour = (byte)HexToBCD((ulong)System.DateTime.Now.Hour, 2);
                byte minute = (byte)HexToBCD((ulong)System.DateTime.Now.Minute, 2);
                byte second = (byte)HexToBCD((ulong)System.DateTime.Now.Second, 2);
                data.Add(hour);
                data.Add(minute);
                data.Add(second);
                data.Add(hour);
                data.Add(minute);
                data.Add(second);


                string trNum = TaxDataTrainNumAndCabNo.TrainType + TaxDataTrainNumAndCabNo.TrainNum.ToString();
                if (trNum == "0")
                {
                    TrainNumAndCabNum trainNum = new TrainNumAndCabNum();
                    trainNum.ShowDialog();
                    trNum = trainNum.TrainNum;
                }
                byte[] trNumByte = System.Text.ASCIIEncoding.Default.GetBytes(trNum);
                int len = trNumByte.Length;
                for (int i = 0; i < len; i++)
                {
                    data.Add(trNumByte[i]);
                }
                for (int i = 0; i < 7 - len; i++)
                {
                    data.Add(0x20);
                }

                string cabNo = TaxDataTrainNumAndCabNo.CabType + TaxDataTrainNumAndCabNo.CabNo;
                if (cabNo == "" || cabNo == null)
                {
                    CabNO cn = new CabNO();
                    cn.ShowDialog();
                    cabNo = cn.CabStr;
                }
                byte[] cabByte = System.Text.ASCIIEncoding.Default.GetBytes(cabNo);//(GPRS_CabNum);
                int len2 = cabByte.Length;
                for (int i = 0; i < 3; i++)
                {
                    data.Add(cabByte[i]);
                }
                for (int i = 4; i >= 0; i--)
                {
                    if (i >= len2 - 3)
                        data.Add(0x20);
                    else
                        data.Add(cabByte[len2 - i - 1]);
                }
                data.Add(0x01);
                data.Add(0x31);
                data.Add(0x31);
                data.Add(0x32);
                for (int i = 0; i < 11; i++)
                {
                    data.Add(0x20);
                }
                for (int i = 0; i < 6; i++)
                {
                    data.Add(0x00);
                }
                data.Add(0x01);
                data.Add(0x01);
                data.Add(0xC1);
                data.Add(0xD0);
                data.Add(0xB3);
                data.Add(0xB5);
                data.Add(0xBD);
                data.Add(0xF8);
                data.Add(0xC2);
                data.Add(0xB7);
                data.Add(0xD4);
                data.Add(0xA4);
                data.Add(0xB8);
                data.Add(0xE6);
                data.Add(0x0D);
                data.Add(0x0A);
                data.Add(0xCF);
                data.Add(0xC2);
                data.Add(0xD7);
                data.Add(0xAF);
                data.Add(0xD5);
                data.Add(0xBE);
                data.Add(0x0D);
                data.Add(0x0A);
                for (int i = 0; i < contentByte.Length; i++)
                {
                    data.Add(contentByte[i]);
                }
                byte[] frameData = data.ToArray();
                byte[] sendData = Unit.PacketData(frameData);
                return sendData;
                // OSP7.Write(sendData, 0, sendData.Length);
            }
            catch (System.Exception ex)
            {
                return null;
            }
        }

        public ulong HexToBCD(ulong phex, uint num)//HEX码转换成BCD码
        {
            int i;
            ulong pdiv, pmul;

            byte[] tmp = new byte[num];
            pdiv = phex;
            for (i = 0; i < num; i++)
            {
                tmp[i] = (byte)(pdiv % 10);
                pdiv = pdiv / 10;
            }
            pmul = 1;
            pdiv = 0;
            for (i = 0; i < num; i++)
            {
                pdiv = pdiv + pmul * tmp[i];
                pmul = pmul * 0x10;
            }
            return pdiv;
        }

        //GPRS模块注册命令
        private void RegisterGPRS(SerialPort OSP)
        {
            ReadedNum = 0;
            string commStr = string.Empty;

            commStr = "ATE0\r\n";
            byte[] sendComm4 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
            try
            {
                OSP.Write(sendComm4, 0, sendComm4.Length);
            }
            catch (Exception ex)
            {

            }
            Delay(1500);
        }
        #endregion

        public void SendDispatchCommand()  //发送调度命令
        {
            if (!OSP7.IsOpen)
            {
                try
                {
                    OSP7.Open();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            Delay(1000);
            if (OSP7.IsOpen)
            {
                if (!UDPConnectStatus)
                {

                    TestDispacthComm = true;
                    TestWirelessTrainNum = false;
                    TestTrainRouteNotice = false;
                    RegisterGPRS(OSP7);

                }
                else
                {
                    TestDispacthComm = true;
                    TestWirelessTrainNum = false;
                    TestTrainRouteNotice = false;
                    byte[] sendData = DispatchCommand();
                    int len = sendData.Length;
                    string commStr = "AT+CIPSEND=" + len.ToString() + "\r\n";
                    byte[] sendComm13 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                    OSP7.Write(sendComm13, 0, sendComm13.Length);
                    Delay(1500);
                    OSP7.Write(sendData, 0, sendData.Length);
                }
            }
        }

        public void SendWirelessTrainNumCommand()   //发送无线车次号上传命令
        {
            Index = 0;
            if (!OSP6.IsOpen)
            {
                try
                {
                    OSP6.Open();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            if (!OSP7.IsOpen)
            {
                try
                {
                    OSP7.Open();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            Delay(5000);
            if (OSP7.IsOpen)
            {
                TestDispacthComm = false;
                TestWirelessTrainNum = true;
                MainFrm.MotherFrm.GSM_RFunTrial = true;
                TestTrainRouteNotice = false;
                if (!UDPConnectStatus)
                {
                    RegisterGPRS(OSP7);
                }
                else
                {
                    ReadedNum = 11;
                    IsReceiveTrainNum = true;
                    // MessageBox.Show("请按无线车次号上传条件发送TAX数据");
                }
            }
        }

        //查找帧头和帧尾
        private int FindDataFrameHead(byte[] arr, byte head1, byte head2, int startIndex, int findLength, bool isFindHead)
        {
            int index = -1;
            {
                for (int i = startIndex; i < findLength; i++)
                {
                    if (arr[i] == head1 && arr[i + 1] == head2)
                    {
                        index = i;
                        break;
                    }
                }
            }
            return index;
        }


        public void SendTrainRouteForenoticeCommand()  //发送列车进路预告命令
        {
            if (!OSP7.IsOpen)
            {
                try
                {
                    OSP7.Open();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            Delay(500);
            if (OSP7.IsOpen)
            {
                if (!UDPConnectStatus)
                {
                    TestDispacthComm = false;
                    TestWirelessTrainNum = false;
                    TestTrainRouteNotice = true;
                    RegisterGPRS(OSP7);
                }
                else
                {
                    TestDispacthComm = false;
                    TestWirelessTrainNum = false;
                    TestTrainRouteNotice = true;
                    byte[] sendData = TrainRouterCommand();
                    int len = sendData.Length;
                    string commStr = "AT+CIPSEND=" + len.ToString() + "\r\n";
                    byte[] sendComm13 = System.Text.ASCIIEncoding.Default.GetBytes(commStr);
                    OSP7.Write(sendComm13, 0, sendComm13.Length);
                    Delay(1500);
                    OSP7.Write(sendData, 0, sendData.Length);
                }
            }
            else
            {
                MessageBox.Show("串口未打开");
            }
        }
    }
}
